package cn.datax.service.data.market.service.impl;

import cn.datax.common.base.BaseServiceImpl;
import cn.datax.common.exception.DataException;
import cn.datax.service.data.market.api.dto.ApiWarnRuleDto;
import cn.datax.service.data.market.api.entity.ApiMaskEntity;
import cn.datax.service.data.market.api.entity.ApiWarnRuleEntity;
import cn.datax.service.data.market.dao.ApiMaskDao;
import cn.datax.service.data.market.dao.ApiWarnRuleDao;
import cn.datax.service.data.market.mapstruct.ApiMaskMapper;
import cn.datax.service.data.market.mapstruct.ApiWarnRuleMapper;
import cn.datax.service.data.market.service.ApiMaskService;
import cn.datax.service.data.market.service.ApiWarnRuleService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 数据API告警规则 服务
 * </p>
 *
 * @author jimmy
 * @since 2021-07-27
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class ApiWarnRuleServiceImpl extends BaseServiceImpl<ApiWarnRuleDao, ApiWarnRuleEntity> implements ApiWarnRuleService {


    @Autowired
    private ApiWarnRuleDao apiWarnRuleDao;

    @Autowired
    private ApiWarnRuleMapper apiWarnRuleMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveApiWarnRule(ApiWarnRuleDto apiWarnRuleDto) {
        ApiWarnRuleEntity apiWarnRuleEntity = apiWarnRuleMapper.toEntity(apiWarnRuleDto);
        // 校验指标唯一
        int n = apiWarnRuleDao.selectCount(Wrappers.<ApiWarnRuleEntity>lambdaQuery().eq(ApiWarnRuleEntity::getMetric, apiWarnRuleEntity.getMetric()).eq(ApiWarnRuleEntity::getApiId,apiWarnRuleEntity.getApiId()));
        if(n > 0){
            throw new DataException("API已进行过配置该指标。");
        }
        apiWarnRuleDao.insert(apiWarnRuleEntity);
    }

    @Override
    public void updateApiWarnRule(ApiWarnRuleDto apiWarnRuleDto) {
        ApiWarnRuleEntity apiWarnRuleEntity = apiWarnRuleMapper.toEntity(apiWarnRuleDto);
        apiWarnRuleDao.updateById(apiWarnRuleEntity);
    }

    @Override
    public ApiWarnRuleEntity getApiWarnRuleById(String id) {
        ApiWarnRuleEntity apiWarnRuleEntity = super.getById(id);
        return  apiWarnRuleEntity;
    }

    @Override
    public void deleteApiWarnRuleById(String id) {
        apiWarnRuleDao.deleteById(id);
    }

    @Override
    public void deleteApiWarnRuleBatch(List<String> ids) {
        apiWarnRuleDao.deleteBatchIds(ids);
    }
}
